import useSettingsStore from './settings'
import useRouteStore from './route'
import useMenuStore from './menu'
import router from '@/router'
import apiUser from '@/api/modules/user'

const useUserStore = defineStore(
  // 唯一ID
  'user',
  () => {
    const settingsStore = useSettingsStore()
    const routeStore = useRouteStore()
    const menuStore = useMenuStore()

    const haveInfo = ref(false)
    const id = ref()
    const account = ref(localStorage.account ?? '')
    const token = ref(localStorage.token ?? '')
    const avatar = ref(localStorage.avatar ?? '')
    const permissions = ref<string[]>([])
    const roles = ref<string[]>([])
    const isLogin = computed(() => {
      if (token.value) {
        return true
      }
      return false
    })

    const nickName = ref('')
    const phoneNumber = ref('')
    const email = ref('')
    const sex = ref('')

    // 登录
    async function login(data: {
      account: string
      password: string
    }) {
      const loginInfo = await apiUser.login(data)
      localStorage.setItem('account', data.account)
      localStorage.setItem('token', loginInfo.token)
      account.value = data.account
      token.value = loginInfo.token
    }
    // 登出
    async function logout(redirect = router.currentRoute.value.fullPath) {
      localStorage.removeItem('account')
      localStorage.removeItem('token')
      localStorage.removeItem('avatar')
      account.value = ''
      token.value = ''
      avatar.value = ''
      permissions.value = []
      routeStore.removeRoutes()
      menuStore.setActived(0)
      haveInfo.value = false
      router.push({
        name: 'login',
        query: {
          ...(router.currentRoute.value.path !== settingsStore.settings.home.fullPath && router.currentRoute.value.name !== 'login' && { redirect }),
        },
      })
    }
    // 获取权限
    async function getPermissions() {
      // const res = await apiUser.permission()
      // permissions.value = res.data.permissions
    }
    // 获取用户信息
    async function getUserInfos() {
      haveInfo.value = true
      let userInfo
      try {
        userInfo = await apiUser.getInfo()
      }
      catch (e) {
        haveInfo.value = false
      }
      localStorage.setItem('avatar', userInfo.user.avatar)
      avatar.value = userInfo.user.avatar !== '' ? import.meta.env.VITE_APP_BASE_API + userInfo.user.avatar : ''
      id.value = userInfo.user.userId
      nickName.value = userInfo.user.nickName
      phoneNumber.value = userInfo.user.phonenumber
      email.value = userInfo.user.email
      sex.value = userInfo.user.sex
      if (userInfo.roles && userInfo.roles.length > 0) {
        roles.value = userInfo.roles
        permissions.value = userInfo.permissions
      }
      else {
        roles.value = ['ROLE_DEFAULT']
      }
    }
    // 修改密码
    async function editPassword(oldPassword: string, newPassword: string) {
      await apiUser.passwordEdit({ oldPassword, newPassword })
    }

    return {
      haveInfo,
      account,
      token,
      avatar,
      permissions,
      isLogin,
      nickName,
      phoneNumber,
      email,
      sex,
      login,
      logout,
      getPermissions,
      getUserInfos,
      editPassword,
    }
  },
)

export default useUserStore
